import datetime

from other.cfg import Config
from other.change_format import change_format
from other.sql_montage import sqlMontage
from other.status import Status
from server.Mysql import MySQL


class overhaul:
    def __init__(self):
        self.cfg = Config()
        self.st = Status()
        self.db = MySQL(self.cfg.res['mysql']['database'], 'overhaul_info')
        self.cf = change_format()
        self.sm = sqlMontage()

    # 查询大修信息
    def get_overhaul_info(self, data):
        result = {'msg': '成功', 'code': 200, 'data': [], 'total': None}
        sqls = f"where `del_flag`='{self.st.get_status('delFlag', '存在')}' "
        sql = ""
        pages = ''
        if data != {}:
            if data.get('pageNum') is not None and data.get('pageSize') is not None:
                if data['pageNum'] != '' and data['pageSize'] != '':
                    pages = " limit {},{}".format(int(data['pageNum']) * int(data['pageSize']) - int(data['pageSize']),
                                                  int(data['pageSize']))
            if data.get('overhaulName') is not None:
                if data['overhaulName'] != '':
                    sql = sql + " and `overhaul_name` like '%{}%'".format(data['overhaulName'])
            if data.get('overhaulCode') is not None:
                if data['overhaulCode'] != '':
                    sql = sql + " and `overhaul_code`='{}'".format(data['overhaulCode'])
            if data.get('status') is not None:
                if data['status'] != '':
                    sql = sql + " and `status`='{}'".format(data['status'])
            if data.get('beginTime') is not None and data.get('endTime') is not None:
                if data['beginTime'] != '' and data['endTime'] != '':
                    sql = (sql + " and ('{}'<=`create_time` and `create_time`<='{}')".
                           format(data['beginTime'], data['endTime']))
        total = self.db.get(sqls + sql)
        result['total'] = len(total)
        if sql != "":
            sql = sqls + sql + ' ORDER BY `order_num` ASC ' + f'{pages}'
        else:
            sql = sqls + ' ORDER BY `order_num` ASC ' + f'{pages}'
        res = self.db.get(sql)
        if res != ():
            for r in res:
                for key, value in r.items():
                    if isinstance(value, datetime.datetime):
                        r[key] = value.strftime("%Y-%m-%d %H:%M:%S")
                result['data'].append(r)
        result = self.cf.changes_format(result)
        return result

    # 新增大修
    def overhaul_info_add(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `overhaul_code`='{data['overhaulCode']}' or `status`='{self.st.get_status('status', '启用')}'"
        g_res = self.db.get(g_sql)
        if g_res != ():
            result['code'] = 500
            for g in g_res:
                if g['overhaul_code'] == data['overhaulCode']:
                    result['msg'] = '大修编号重复'
                if g['status'] == self.st.get_status('status', '启用'):
                    result['msg'] = '大修已进行，添加失败'
                    return result
        else:
            data['create_by'] = userInfo['userName']
            data['create_time'] = times
            add_sql = self.sm.add_sql_data(data, 'overhaul_info')
            # print('add_sql', add_sql)
            self.db.adds(add_sql, 'overhaul_info')
        return result

    # 修改大修
    def overhaul_info_edit(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `overhaul_code`='{data['overhaulCode']}' or `status`='{self.st.get_status('status', '启用')}'"
        g_res = self.db.get(g_sql)
        ff = False
        if g_res != ():
            for g in g_res:
                if g['status'] == self.st.get_status('status', '启用'):
                    if g['overhaul_info_id'] != data['overhaulInfoId']:
                        if data.get('status') is not None and data['status'] != '':
                            if data['status'] == self.st.get_status('status', '启用'):
                                result['code'] = 500
                                result['msg'] = '大修已进行，修改失败'
                                return result
                            else:
                                if 'createTime' in data:
                                    del data['createTime']
                                data['update_by'] = userInfo['userName']
                                data['update_time'] = times
                                edit_sql = self.sm.edit_sql_data(data, 'overhaul_info', 'overhaul_info_id',
                                                                 data['overhaulInfoId'])
                                self.db.edits(edit_sql, 'overhaul_info')
                                return result
            for gg in g_res:
                if gg['overhaul_info_id'] == data['overhaulInfoId']:
                    ff = True
                else:
                    result['code'] = 500
                    result['msg'] = '大修编号重复'
                    break
        else:
            ff = True
        if ff:
            if 'createTime' in data:
                del data['createTime']
            data['update_by'] = userInfo['userName']
            data['update_time'] = times
            edit_sql = self.sm.edit_sql_data(data, 'overhaul_info', 'overhaul_info_id', data['overhaulInfoId'])
            self.db.edits(edit_sql, 'overhaul_info')
        return result

    # 修改大修状态
    def overhaul_info_edit_status(self, data, userInfo):
        result = {'msg': '成功', 'code': 200}
        times = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        g_sql = f"where `status`='{self.st.get_status('status', '启用')}'"
        g_res = self.db.get(g_sql)
        ff = False
        if g_res != ():
            for g in g_res:
                if g['status'] == self.st.get_status('status', '启用'):
                    if g['overhaul_info_id'] != data['overhaulInfoId']:
                        if data.get('status') is not None and data['status'] != '':
                            if data['status'] == self.st.get_status('status', '启用'):
                                result['code'] = 500
                                result['msg'] = '大修已进行，修改失败'
                                return result
            for gg in g_res:
                if gg['overhaul_info_id'] == data['overhaulInfoId']:
                    ff = True
                else:
                    result['code'] = 500
                    result['msg'] = '大修编号重复'
                    break
        else:
            ff = True
        if ff:
            if 'createTime' in data:
                del data['createTime']
            data['update_by'] = userInfo['userName']
            data['update_time'] = times
            edit_sql = self.sm.edit_sql_data(data, 'overhaul_info', 'overhaul_info_id', data['overhaulInfoId'])
            self.db.edits(edit_sql, 'overhaul_info')
        return result

    # 删除大修
    def overhaul_info_del(self, data):
        pass
